<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="设备编号" prop="deviceCode"  >
        <el-select
        v-model="formData.deviceCode"
        placeholder="请选择设备编号"
        remote
        reserve-keyword
        @change="changeDeviceCode"
        :loading="detLoading"
        class="!w-220px"
      >
    <el-option
      v-for="item in DeviceMessageList"
      :key="item.id"
      :label="item.deviceCode"
      :value="item.deviceCode"
    />
    </el-select>
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="formData.deviceName" placeholder="请输入设备名称" disabled  class="!w-220px"/>
      </el-form-item>
      <el-form-item label="设备类型" prop="dictDeviceType">
        <el-select v-model="formData.dictDeviceType" placeholder="请输入设备类型" disabled class="ipWidth icon">
          <el-option
            v-for="dict in getIntDictOptions('dict_device_type')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="问题描述" prop="problemDescription">
        <el-input 
        v-model="formData.problemDescription" 
        placeholder="请输入问题描述"  
        type="textarea" 
        class="!w-220px"
        maxlength="200"
        show-word-limit
        />
      </el-form-item>
      <el-form-item label="附件上传">
        <UploadFile
          v-model="fileList"
          :limit="1"
          :fileSize="200"
          :fileType="[ 'pdf', 'png', 'jpg']"
          @update:modelValue="uploadFileRes"
        />
      </el-form-item>
      <el-form-item label="原因分析" prop="originalAnalysis">
        <el-input 
        v-model="formData.originalAnalysis" 
        placeholder="请输入原因分析" 
        type="textarea" 
        class="!w-220px"
        maxlength="200"
        show-word-limit
        />
      </el-form-item>
      <el-form-item label="处理结果" prop="processingResults">
        <el-input 
        v-model="formData.processingResults"
        placeholder="请输入处理结果" 
        type="textarea"
        class="!w-220px"
        maxlength="200"
        show-word-limit
        />
      </el-form-item>
      <el-form-item label="状态" prop="dictRepairsStatus">
        <el-select v-model="formData.dictRepairsStatus" placeholder="请输入设备类型"  class="ipWidth">
          <el-option
            v-for="dict in getIntDictOptions('dict_repairs_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
  <template #footer>
  <el-button @click="submitForm" type="primary" :disabled="formLoading">保存</el-button>
  <el-button @click="close">关闭</el-button>
  </template>
</Dialog>
</template>
<script setup>
import { getIntDictOptions } from '@/utils/dict'
import * as DeviceRepairsApi from '@/api/produce/deviceManagement/deviceRepairs'
// import * as deviceArchives from '@/api/config/deviceArchives'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const dialogTitle = ref('') // 弹窗的标题

const formData = ref({
  id: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  dictDeviceType: undefined,
  problemDescription: undefined,
  dictRepairsStatus: undefined,
  creatorName:undefined,
  fileId: undefined,
  fileName: undefined,
  filePath:undefined,
  explain: undefined,
  originalAnalysis: undefined,
  processingResults:undefined,
})

const formRules = reactive({
  deviceCode: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
  problemDescription: [{ required: true, message: '问题描述不能为空', trigger: 'blur' }],
  dictRepairsStatus: [{ required: true, message: '报修状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const fileList =ref([])

// /** 打开弹窗 */
const open = async (type, id) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  fileList.value=[]
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceRepairsApi.getDeviceRepairs(id)
      if ([null,undefined,''].indexOf(formData.value.fileName)===-1) {
        fileList.value.push({
          name: formData.value.fileName,
          url: formData.value.filePath
        })
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/**文件上传返回 */
const uploadFileRes = async(data) => {
  console.log(JSON.parse(data))
  if (JSON.parse(data).length) {
    const res = JSON.parse(data)
    formData.value.fileName = res[0].name
    formData.value.filePath = res[0].url
    
  } else {
    fileList.value = []
    formData.value.fileName = ''
    formData.value.filePath = ''
  }
}
console.log(formRef.value)
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await DeviceRepairsApi.createDeviceRepairs(data)
      console.log('create',data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceRepairsApi.updateDeviceRepairs(data)
      console.log('update',data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

//获取设备编码、信息等
const DeviceMessageList = ref([])
const detLoading = ref(false)
const getDeviceMessageList = async()=>{
  let data = await DeviceRepairsApi.getDeviceMessageList()
  DeviceMessageList.value = data
  detLoading.value = false
}

//选择设备编号时,自动填充
const changeDeviceCode=(val)=>{
  formData.value.deviceCode = val
  DeviceMessageList.value.forEach(item=>{
      if(item.deviceCode===val){
        formData.value.dictDeviceType=item.dictDeviceType
        formData.value.deviceName=item.deviceName
      }
    })
}


/**关闭 */
const close = () => {
  fileList.value = []
  resetForm()
  dialogVisible.value = false
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceCode: undefined,
    deviceName: undefined,
    dictDeviceType: undefined,
    problemDescription: undefined,
    dictRepairsStatus: undefined,
    creatorName:undefined,
    fileId: undefined,
    fileName: undefined,
    fileUrl:undefined,
    explain: undefined,
    processingResults:undefined,
  }
  formRef.value?.resetFields()
}
//初始化
onMounted(()=>{
  getDeviceMessageList()
})
</script>

<style scoped>
.routeHeader {
  width: 100%;
  border-top: 1px solid #969696;
  border-bottom: 1px solid #969696;
  display: flex;
  align-items: center;
  padding: 10px 0;
} 

.ipWidth{
  width: 240px;
}
.txWidth{
  width: 500px;
}

::v-deep .icon .el-input__suffix-inner {
  display: none !important;
}
</style>
